using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using XUCore.Extensions;
using XUCore.WeChat.Enterprise.Apis.Token;

namespace XUCore.WeChat.Enterprise
{
    /// <summary>
    /// 企业微信号AccessToken管理器
    /// </summary>
    public class EnterpriseWeChatTokenManager : IEnterpriseWeChatTokenManager
    {
        private readonly EnterpriseWeChatFuncs weChatFuncs;
        private readonly IServiceProvider serviceProvider;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="weChatFuncs"></param>
        /// <param name="serviceProvider"></param>
        public EnterpriseWeChatTokenManager(EnterpriseWeChatFuncs weChatFuncs, IServiceProvider serviceProvider)
        {
            this.weChatFuncs = weChatFuncs;
            this.serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 获取企业微信的Access Token
        /// </summary>
        /// <param name="suiteId"></param>
        /// <param name="corpId"></param>
        /// <param name="agentId"></param>
        /// <returns></returns>
        public virtual async Task<string> GetAccessTokenAsync(string suiteId, string corpId, int agentId)
        {
            (_, _, var agent) = weChatFuncs.GetEnterpriseWeChatAgentOptions(suiteId, corpId, agentId);

            string token = weChatFuncs?.GetEnterpriseWeChatAccessTokenByCorpId($"{suiteId}{corpId}{agentId}");
            if (string.IsNullOrEmpty(token))
            {
                IEnterpriseTokenApi tokenApi = serviceProvider.GetService<IEnterpriseTokenApi>();
                EnterpriseTokenApiResult result = await tokenApi.GetAsync(corpId, agent.AgentSecret);
                if (!result.IsSuccess())
                {
                    throw new WeChatSdkException($"suiteId：{suiteId} corpId：{corpId} agentId：{agentId} {result.Message}");
                }
                weChatFuncs?.CacheEnterpriseWeChatAccessToken($"{suiteId}{corpId}{agentId}", result.access_token);
                return result.access_token;
            }
            return token;
        }
    }
}